package com.kevis.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userinfo") // 得到redis中的存储过的user信息，返回给子系统的session中
    public Object userInfo(@RequestParam("token") String token){
        // 拿着其他域名转发过来的token去redis里查
        Object loginUser = redisTemplate.opsForValue().get(token);
        return loginUser;
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("url") String url,
                            Model model
    , @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            return "redirect:" + url + "?token=" + sso_token;
        }
        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/doLogin") // server端统一认证
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          //HttpSession session,
                          HttpServletResponse response,
                          @RequestParam(value="url",required = false) String url){
        // 确认用户后，生成cookie、redis中存储 // if内代表取查完数据库了
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){//简单认为登录正确
            // 登录成功跳转 跳回之前的页面
            //这边不能用session,因为域名不一样，对方访问不到，还是没有登录就会跳回来
            //session.setAttribute("loginUser",username);


            String uuid = UUID.randomUUID().toString().replace("-", "");
            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);
            //存放到redis
            redisTemplate.opsForValue().set(uuid,username);
            return "redirect:" + url + "?token=" + uuid;
        }
        // 登录失败
        return "login";
    }
}
